package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.mapper.UserAddressMapper;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    UserAddressMapper userAddressMapper;

    @Override
    public UserInfo login(UserInfo info) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();

        wrapper.eq("login_name",info.getLoginName());

        String passwd = info.getPasswd();
        String encrypt = MD5.encrypt(passwd);
        wrapper.eq("passwd",encrypt);

        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        return userInfo;
    }

    @Override
    public Map<String, Object> handleLoginSuccess(UserInfo userInfo, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<>();

        //1、用户登录成功以后，生成一个唯一令牌(token),标识用户身份，用户id，到底是谁，存在redis中
        //前端只要收到了返回结果，自己就会存cookie，而且放大了作用域
        String token = UUID.randomUUID().toString().replace("-", "");
        map.put("token",token);
        //nickName
        //userInfo == response.data.data
        map.put("nickName",userInfo.getNickName());

        //2、将用户登录的信息存入redis

        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userId",userInfo.getId());
        String ip = IpUtil.getIpAddress(request);
        hashMap.put("ipAddr",ip);

        try {
            String string = new ObjectMapper().writeValueAsString(hashMap);
            operations.set(RedisConst.USER_LOGIN_KEY_PREFIX + token,string,RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public void logout(String token) {
        String s = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(s);
    }

    @Override
    public List<UserAddress> getUserAddressListByUserId(String userId) {
        QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",Long.parseLong(userId));
        List<UserAddress> addressList = userAddressMapper.selectList(wrapper);
        return addressList;
    }
}
